package com.alibaba.citrus.cr.order.open.api.facade.service.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.unified.inventory.contants.FeaturesKey;
import com.alibaba.cz.base.tool.FeatureUtil;
import com.alibaba.fastjson.JSON;
import com.epoch.app.crunifiedinventory.api.allocateorderwrite.service.AllocateOrderWriteService;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderCreateRequest;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderScItemDetailDTO;
import com.epoch.app.crunifiedinventory.model.enums.AllocateOrderStatus;
import com.epoch.app.crunifiedinventory.sdo.AllocateOrderDetailSDO;
import com.epoch.app.mninventorycenter.model.dto.*;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 调拨单创建handler
 *
 * @author mingyang
 * @since 2024/01/04
 */
public abstract class AbstractAllocateOrderCreateHandler {

    @Resource
    AllocateOrderWriteService allocateOrderWriteService;

    /**
     * 是否支持
     * @param request
     * @return
     */
    public abstract Boolean support(TransferOrderCreateRequest request);

    /**
     * handle前的check
     * @param request
     */
    public void check(TransferOrderCreateRequest request) {
        // 有需要检查子类重写
    }

    /**
     * 处理
     * @param request
     * @param scItemInfoMap
     * @param receiveLogicWareId
     * @param deliveryLogicWareId
     * @return
     */
    public abstract TransferOrderCreateResponse handle(TransferOrderCreateRequest request,
                                                       Map<String, ScItemResponse> scItemInfoMap,
                                                       WarehouseQueryResponse receiveLogicWareId,WarehouseQueryResponse deliveryLogicWareId);
    protected String getFeatures(WarehouseQueryResponse receiveLogicWare, WarehouseQueryResponse deliveryLogicWare) {
        HashMap<String, String> newFeaturesMap = new HashMap<>();
        if (receiveLogicWare == null || deliveryLogicWare == null) {
            return null;
        }
        Map<String, String> receiveLogicWareMap = receiveLogicWare.getFeatures();
        Map<String, String> deliveryLogicWareMap = deliveryLogicWare.getFeatures();

        if(receiveLogicWareMap.get("sapCompanyCode") != null){
            newFeaturesMap.put("receiveCompanyCode", receiveLogicWareMap.get("sapCompanyCode"));
        }
        if(receiveLogicWareMap.get("sapOrgCode") != null){
            newFeaturesMap.put("receiveSapOrgCode", receiveLogicWareMap.get("sapOrgCode"));
        }
        if(deliveryLogicWareMap.get("sapCompanyCode") != null){
            newFeaturesMap.put("shipCompanyCode", deliveryLogicWareMap.get("sapCompanyCode"));
        }
        if(deliveryLogicWareMap.get("sapOrgCode") != null){
            newFeaturesMap.put("shipSapOrgCode", deliveryLogicWareMap.get("sapOrgCode"));
        }



        return FeatureUtil.toString(newFeaturesMap);
    }

    protected String getFeaturesNew(WarehouseQueryResponse receiveLogicWare, WarehouseQueryResponse deliveryLogicWare, TransferOrderCreateRequest request) {
        HashMap<String, String> newFeaturesMap = new HashMap<>();
        if (receiveLogicWare == null || deliveryLogicWare == null) {
            return null;
        }
        Map<String, String> receiveLogicWareMap = receiveLogicWare.getFeatures();
        Map<String, String> deliveryLogicWareMap = deliveryLogicWare.getFeatures();

        if(receiveLogicWareMap.get("sapCompanyCode") != null){
            newFeaturesMap.put("receiveCompanyCode", receiveLogicWareMap.get("sapCompanyCode"));
        }
        if(receiveLogicWareMap.get("sapOrgCode") != null){
            newFeaturesMap.put("receiveSapOrgCode", receiveLogicWareMap.get("sapOrgCode"));
        }
        if(deliveryLogicWareMap.get("sapCompanyCode") != null){
            newFeaturesMap.put("shipCompanyCode", deliveryLogicWareMap.get("sapCompanyCode"));
        }
        if(deliveryLogicWareMap.get("sapOrgCode") != null){
            newFeaturesMap.put("shipSapOrgCode", deliveryLogicWareMap.get("sapOrgCode"));
        }
        if (StringUtils.isNotBlank(request.getShipMethodCode())) {
            if ("02".equals(request.getShipMethodCode()) || "03".equals(request.getShipMethodCode())) {
                newFeaturesMap.put("freightYardReceive", "true");
            }
        }

        return FeatureUtil.toString(newFeaturesMap);
    }




    protected TransferOrderCreateResponse getAllocateOrderCreateResponse(String code , String thirdAllocateOrderId, List<AllocateOrderDetailSDO> allocateOrderDetailSDOS){
        TransferOrderCreateResponse transferOrderCreateResponse = new TransferOrderCreateResponse();
        if(CollectionUtil.isNotEmpty(allocateOrderDetailSDOS)){
            List<TransferOrderCreateDetailResponse> collect = allocateOrderDetailSDOS.stream().map(x -> {
                TransferOrderCreateDetailResponse transferOrderCreateDetailResponse = new TransferOrderCreateDetailResponse();
                transferOrderCreateDetailResponse.setDetailNo(x.getLineNo());
                transferOrderCreateDetailResponse.setOutDetailLineNo(x.getThirdLineNo());
                return transferOrderCreateDetailResponse;
            }).collect(Collectors.toList());
            transferOrderCreateResponse.setTransferOrderCreateDetailResponseList(collect);
        }
        transferOrderCreateResponse.setThirdAllocateOrderCode(thirdAllocateOrderId);
        transferOrderCreateResponse.setTransferOrderCode(code);
        transferOrderCreateResponse.setThirdAllocateOrderCode(thirdAllocateOrderId);
        return transferOrderCreateResponse;
    }

    protected Date strToDate(String strDae) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        try {
            parse = df.parse(strDae);
        } catch (ParseException e) {
            throw new FacadeException("时间格式转换异常");
        }
        return parse;
    }

    protected AllocateOrderCreateRequest getAllocateOrderCreateRequest(TransferOrderCreateRequest transferOrderCreate,
                                                                       Map<String, ScItemResponse> scItemInfoMap,
                                                                       WarehouseQueryResponse receiveLogicWareId, WarehouseQueryResponse deliveryLogicWareId){
        AllocateOrderCreateRequest allocateOrderCreate = new AllocateOrderCreateRequest();
        allocateOrderCreate.setBusinessType(transferOrderCreate.getBusinessType());
        allocateOrderCreate.setFromSys(transferOrderCreate.getFromSys());
        allocateOrderCreate.setSubmitFlag(Boolean.parseBoolean(transferOrderCreate.getSubmitFlag()));
        allocateOrderCreate.setType(transferOrderCreate.getTransferOrderType());
        allocateOrderCreate.setReturnOrder(Boolean.parseBoolean(transferOrderCreate.getReturnFlag()));

        allocateOrderCreate.setReceiveWareHouseId(receiveLogicWareId.getParentId());
        allocateOrderCreate.setReceiveAreaId(receiveLogicWareId.getId());
        allocateOrderCreate.setShipWareHouseId(deliveryLogicWareId.getParentId());
        allocateOrderCreate.setShipAreaId(deliveryLogicWareId.getId());

        allocateOrderCreate.setDocDate(transferOrderCreate.getOrderDate());
        allocateOrderCreate.setExpectedDeliveryDate(strToDate(transferOrderCreate.getExpectedDeliveryDate()));
        allocateOrderCreate.setShipMethod(Integer.parseInt(transferOrderCreate.getShipMethodCode()));
        allocateOrderCreate.setRemark(transferOrderCreate.getHeadRemark());
        allocateOrderCreate.setRequestId(transferOrderCreate.getRequestId());
        allocateOrderCreate.setAllocateApplyOrderId(transferOrderCreate.getAllocateApplyOrderId());
        allocateOrderCreate.setThirdAllocateOrderId(transferOrderCreate.getThirdAllocateOrderId());

        allocateOrderCreate.setAllocateApplyOrderCode(transferOrderCreate.getAllocateApplyOrderCode());
        allocateOrderCreate.setApplyOrgId(transferOrderCreate.getApplyOrgId());
        allocateOrderCreate.setRelatedAllocateOrderCode(transferOrderCreate.getRelatedAllocateOrderCode());
        allocateOrderCreate.setFulfillmentTypeCode(transferOrderCreate.getFulfillmentTypeCode());

        allocateOrderCreate.setPriority("100".equals(transferOrderCreate.getPriority()) ? 100 : 1);
        // 0-是，1-否 不传的情况下默认“是”
        allocateOrderCreate.setAutoFulfillment(Boolean.FALSE.equals(transferOrderCreate.getAutoFulfillment()) ? 0 : 1);
        allocateOrderCreate.setOrderTag(transferOrderCreate.getOrderTag());
        allocateOrderCreate.setTakeEffectDate(transferOrderCreate.getTakeEffectDate());
        allocateOrderCreate.setProductGroup(transferOrderCreate.getProductGroupCode());
        allocateOrderCreate.setTransferWarehouseId(transferOrderCreate.getTransferWarehouseId());
        //设置bizFeatures
        allocateOrderCreate.setBizFeatures(transferOrderCreate.getBizFeatures());
        //新创建人字段
        allocateOrderCreate.setCreatorName(transferOrderCreate.getCreator());

        List<TransferOrderDetailRequest> transferOrderDetailList = transferOrderCreate.getTransferOrderDetailList();
        List<AllocateOrderScItemDetailDTO> collect = transferOrderDetailList.stream().map(x -> {
            ScItemResponse scItemResponse = scItemInfoMap.get(x.getGoodsCode());
            AllocateOrderScItemDetailDTO allocateOrderScItemDetail = new AllocateOrderScItemDetailDTO();
            allocateOrderScItemDetail.setScItemId(scItemResponse.getScItemId());
            allocateOrderScItemDetail.setScItemCode(x.getGoodsCode());
            allocateOrderScItemDetail.setTitle(scItemResponse.getTitle());
            allocateOrderScItemDetail.setQuantity(x.getQuantity());
            allocateOrderScItemDetail.setUnit(x.getUnit());
            allocateOrderScItemDetail.setProductDate(x.getProductDate());
            allocateOrderScItemDetail.setRemark(x.getLineRemark());
            allocateOrderScItemDetail.setThirdLineNo(x.getOutDetailLineNo());
            allocateOrderScItemDetail.setRelatedAllocateSubOrderId(x.getRelatedAllocateSubOrderNo());
            allocateOrderScItemDetail.setAllocateApplyOrderLineNo(x.getAllocateApplyOrderLineId());
            if (StringUtils.isNotBlank(x.getBizFeatures())) {
                Map<String, String> bizFeaturesMap = FeatureUtil.fromString(x.getBizFeatures());
                //子单的业务扩展信息也写入收货仓id
                bizFeaturesMap.put(FeaturesKey.RECEIVE_AREA_ID,receiveLogicWareId.getId());
                allocateOrderScItemDetail.setBizFeatures(FeatureUtil.toString(bizFeaturesMap));
            }
            return allocateOrderScItemDetail;
        }).collect(Collectors.toList());
        allocateOrderCreate.setAllocateOrderScItemDetails(collect);
        return allocateOrderCreate;
    }
}


